//
// Created by china on 25-1-10.
//

#include "FriendModel.h"

bool FriendModel::instert(const MySQLTable::Friend& addFriend) {
    LOG_INFO<<"AddFriendModel::instert";

    if(addFriend.userid == -1 || addFriend.friendid == -1){
        LOG_ERROR<<"添加好友错误";
        return false;
    }

    char sql1[512];
    char sql2[512];
    std::sprintf(sql1, "INSERT INTO friend(userid,friendid) values(%d,%d)", addFriend.userid,addFriend.friendid);
    std::sprintf(sql2, "INSERT INTO friend(userid,friendid) values(%d,%d)",addFriend.friendid, addFriend.userid);

    auto pool = Pool::getInstance();
    auto conn = pool->getFreeConn();
    if(conn->update(sql1) && conn->update(sql2)){
        return true;
    }
    return false;
}

std::vector<struct MySQLTable::User> FriendModel::query(const MySQLTable::User& user) {
    LOG_INFO<<"AddFriendModel::query";

    std::vector<struct MySQLTable::User> vec;
    if(user.id == -1 ){
        LOG_ERROR<<"不是有效用户";
        return vec;
    }
    //user和friend表的联合查询
    //select a.id,a.name,a.state from user a inner join friend b on b.friendid = a.id where b.userid = user.id;
    char sql[512];
    std::sprintf(sql, "SELECT a.id,a.name,a.state FROM user a INNER JOIN friend b ON b.friendid = a.id WHERE b.userid = %d ", user.id);

    auto pool = Pool::getInstance();
    auto conn = pool->getFreeConn();
    MYSQL_RES* res = conn->query(sql);
    if(res != nullptr){
        MYSQL_ROW row;
        while ((row = mysql_fetch_row(res)) != nullptr){
            MySQLTable::User user;
            user.id = atoi(row[0]);
            user.name = row[1];
            user.state = row[2];
            vec.push_back(user);
        }
    }
    //释放资源
    mysql_free_result(res);
    return vec;
}






